﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Drawing;

namespace Tesla.Util.UIUtilities
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:TeslaTextBox runat=server></{0}:TeslaTextBox>")]

    public class TeslaTextBox : TextBox
    {

        #region Variables
       // static int i = 0;
        private const string _Text_BACK_COLOR_KEY = "TextBackColor";
        //bool isDirty = false;
        #endregion


        #region Custom Properties

        /// <summary>
        ///PUBLIC PROPERTY TO SET OR GET THE DIRTY PROPERTY OF THE CONTROL
        /// </summary>

        //[Category("Behavior")]
        //[DefaultValue(true)]
        //[Localizable(true)]
        //public bool Dirty
        //{
        //    get
        //    {
        //        return ViewState["isDirty"] == null ? false : (bool)ViewState["IsDirty"];
        //        //return (bool)ViewState["IsDirty"];

        //    }
        //    set
        //    {
        //        ViewState["isDirty"] = value;
        //    }
        //}


        /// <summary>
        ///PUBLIC PROPERTY TO SET OR GET THE TEXT OF THE CONTROL
        /// </summary>
        [Category("Behavior")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? "[" + this.ID + "]" : s);
            }

            set
            {
                ViewState["Text"] = value;
            }
        }

        /// <summary>
        ///PUBLIC PROPERTY TO SET OR GET THE READ ONLY PROPERTY OF THE CONTROL.A LABEL WILL BE DISPLAYED INCASE
        ///THE READ ONLY PROPERTY IS SET TO TRUE.
        /// </summary>
        
        
        public bool ReadOnly
        {
            get
            {
                return (bool)base.ReadOnly;
            }
            set
            {
                base.ReadOnly = value;
            }
        }



        /// <summary>
        ///PUBLIC PROPERTY TO SET OR GET THE MANDATORY PROPERTY OF THE CONTROL.IF SET TO TRUE,
        ///ALERT WILL BE SENT TO THE USER
        ///INCASE THE TEXT VALUE IS LEFT EMPTY.
        /// </summary>
        
        public bool Mandatory
        {
            get
            {
                return ViewState["Mandatory"] == null ? false : (bool)ViewState["Mandatory"];
                
            }
            set
            {
                ViewState["Mandatory"] = value;
            }
        }
        #endregion
        
        
        #region Overriden Events

        protected override void OnLoad(EventArgs e)
        {
            SetUIProperties();
           
            base.OnLoad(e);

        }

        void SetUIProperties()
        {
            //if (i == 0)
            //{
            //    Dirty = false;
               
            //    i++;
            //}

            BackColor = System.Drawing.ColorTranslator.FromHtml(ControlUtilities.GetConfigInformation(_Text_BACK_COLOR_KEY));
            //Focus();

        }

        protected override void RenderContents(HtmlTextWriter writer)
        {

            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
            writer.RenderEndTag();
            // base.RenderContents(writer);
        }


        protected override void OnPreRender(EventArgs e)
        {
            if(! Page.ClientScript.IsClientScriptBlockRegistered("ValidateControl"))
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "ValidateControl", "function ValidateText(ct1)" + "{var x=document.getElementById(ct1).value;var y=document.getElementById(ct1).value.length; if(x==\"\")" + "alert('The field cannot be empty.Please enter a valid text');} ", true);
            if(! Page.ClientScript.IsClientScriptBlockRegistered("ValidateTextbox"))
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Setting_Dirty", "function Setting_Dirty(ct1)" + "{if(document.getElementById(ct1) != null){document.getElementById(ct1).setAttribute(\"_Dirty\",\"true\");}}", true);
            if (!Page.ClientScript.IsClientScriptBlockRegistered("isNumberKey"))
                Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "isNumberKey", "function isNumberKey(evt)" + "{var charCode = (evt.which)?evt.which : event.keyCode;if ((charCode >= 34 && charCode <= 42) || (charCode > 62 && charCode < 96) || (charCode >= 44 && charCode <= 59) || (charCode > 96 && charCode < 125) || (charCode == 95) || (charCode == 8) || (charCode == 32) || (charCode == 13) || (charCode == 125)) return true; else return false;}", true);

            
            //base.OnPreRender(e);
        }

        

        protected override void Render(HtmlTextWriter writer)
        {
            bool isValid = true;
            checkValidText();
            if (this.ReadOnly)
            {
                writer.Write(this.Text);
            }
            else
            {
                if (this.Mandatory)
                {
                    this.Attributes.Add("OnBlur", "ValidateText('" + this.ID + "')");
                }
                this.Attributes.Add("onkeypress", "return isNumberKey(event)");
                this.Attributes.Add("oncopy", "return false");
                this.Attributes.Add("onpaste", "return false");
                this.Attributes.Add("onChange", "Setting_Dirty('" + this.ID + "')");
                base.Render(writer);
            }
            
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
            writer.AddAttribute("_Dirty", "false");
        }

        protected void checkValidText()
        {
            string invalidText = this.Text;
            string validText = string.Empty;
            int charactervalue;
            int counter=0;
            CharEnumerator charEnum = invalidText.GetEnumerator();
            while (charEnum.MoveNext())
            {
                charactervalue = Convert.ToInt32(invalidText[counter]);
                if ((charactervalue >= 34 && charactervalue <= 42) || (charactervalue > 62 && charactervalue < 96) || (charactervalue >= 44 && charactervalue <= 59) || (charactervalue > 96 && charactervalue < 125) || (charactervalue == 95) || (charactervalue == 8) || (charactervalue == 32) || (charactervalue == 13) || (charactervalue == 125))
                {
                    validText = validText + (invalidText[counter]).ToString();
                }
                counter++;
            }
            this.Text = validText;

        }
       
        #endregion

    }
}

